#  Copyright (c) 2021
#  User:SDUFE-Zhaocheng Lu
#  File:main.py
#  Date:2021/08/16 23:30:16
import datetime
import time
from get_user_data import get_user_data
from start_sign import QD
import smtplib, lib
from email.mime.text import MIMEText
from email.utils import formataddr
import threading

contents = ''' <ul style="height: 60px;border-bottom: solid 1px #e6e6e6;"><h1 tabindex="0" style="float: left; line-height: 60px; font-size: 20px; padding: 0px 20px;">山东财经大学区块链打卡辅助平台</h1></ul>
                <div style="width: 100%;min-height: 300px;display: flex;justify-content: center;align-items: center;flex-direction: column;">
                <h2 style="font-size: 36px;">{}</h2><span style="margin-top: 40px">更多详细信息，前往<a style="color: #2391c6;text-decoration: none;font-weight: bold;font-size: 24px;"href="http://yq.py00.top">打卡辅助平台</a>查看</span>
                </div>
            '''


def send_result(my_user, content=None):
    my_sender = 'i@py00.top'  # 发件人邮箱账号
    my_pass = 'UhiP8D8i8w6gQsXg'  # 发件人邮箱密码
    server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码

    def mail():
        ret = True
        try:
            if not content:
                msg = MIMEText(contents.format('打卡成功\t' + str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))),
                               'html',
                               'utf-8')
            else:
                msg = MIMEText(contents.format(content), 'html', 'utf-8')
            msg['From'] = formataddr(["NOTICE！", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
            msg['To'] = formataddr(["FK", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
            msg['Subject'] = "疫情打卡结果"  # 邮件的主题，也可以说是标题
            server.sendmail(my_sender, [my_user, ], msg.as_string())
            server.quit()  # 关闭连接
        except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
            ret = False
        return ret

    ret = mail()
    if ret:
        print("邮件发送成功")
    else:
        print("邮件发送失败")


def main_func(usr_data):
    today = datetime.date.today()
    qd_fun = QD(usr_data)
    login_status = qd_fun.login_start()
    if login_status:
        print(usr_data['school_id'], '登录:\t成功')
        if not qd_fun.check_sign():
            print(usr_data['school_id'], '签到:\t略过')
            lib.pass_list.append(usr_data['school_id'])
            return -1
        qd_fun.qd_start()
        if qd_fun.qd_status:
            print(usr_data['school_id'], '签到:\t成功')
            lib.success_list.append(usr_data['school_id'])
        else:
            print(usr_data['school_id'], '签到:\t失败')
            lib.error_list.append(usr_data['school_id'])
    else:
        print(usr_data['school_id'], '登录:\t失败')
        lib.error_list.append(usr_data['school_id'])
    crossDays = (usr_data['usr_info']['expireTime'] - today).days
    more = '还有%s天过期，请您及时续费！<br>' % crossDays if crossDays <= 2 else ''
    if not qd_fun.qd_status or not qd_fun.login_status:
        send_result(usr_data['email'], more + '区块链打卡状态：\t打卡失败')
        return 0
    else:
        send_result(usr_data['email'], more + '区块链打卡状态：\t打卡成功')
        return 1


if __name__ == '__main__':
    usr_data_list = get_user_data(where='active=true')
    threads = []
    for usr_data in usr_data_list:
        main_func(usr_data)
        # threads.append(
        #     threading.Thread(target=main_func, args=(usr_data,))
        # )
    # for thread in threads:
    #     thread.start()
    # for thread in threads:
    #     thread.join()

    send_result('1256234567@qq.com',
                '打卡成功：{}\n打卡失败：{}\n打卡忽略：{}'.format('<br>'.join(lib.success_list), '<br>'.join(lib.error_list),
                                                   ','.join(lib.pass_list)))
